package com.example.cameraxtext

import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.util.Size
import android.view.Surface.*
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.Executors


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 方式一
        val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager

        try {
            val cameraIdList =
                (getSystemService(Context.CAMERA_SERVICE) as CameraManager).cameraIdList
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }

        //1, 请求 CameraProvider
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        //2,检查 CameraProvider 可用性
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider = cameraProviderFuture.get()
            bindPreview(cameraProvider)
        }, ContextCompat.getMainExecutor(this))
    }

    //3选择相机并绑定生命周期和用例
    fun bindPreview(cameraProvider: ProcessCameraProvider) {
        // 在绑定前先要解绑
        cameraProvider.unbindAll()
        //选择前置摄像头
        val cameraSelector: CameraSelector = CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_FRONT)
            .build()
        //预览在这设置
        val preview: Preview = Preview.Builder().apply {
            //设置预览角度
            setTargetRotation(ROTATION_0)
        }
            .build()

        preview.setSurfaceProvider(viewFinder.surfaceProvider)
        val imageAnalysis = ImageAnalysis.Builder()
            .setTargetResolution(Size(1280, 720))
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build()

        imageAnalysis.setAnalyzer(Executors.newSingleThreadExecutor(), { image ->
            val rotationDegrees = image.imageInfo.rotationDegrees
            val yuv420ToNv21 = Utils.yuv420ToNv21(image)



            image.close()
        })

        var camera = cameraProvider.bindToLifecycle(
            this as LifecycleOwner,
            cameraSelector,
            imageAnalysis,
            preview
        )
    }


}